package com.opengroupe.recognize;

import java.io.IOException;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;

public class MainActivity extends Activity {

	final static String LOG_TAG = "Recognize_MainActivity";
	private SurfaceView surface_view;  
	private Camera mCamera;
	SurfaceHolder.Callback sh_ob = null;
	SurfaceHolder surface_holder        = null;
	SurfaceHolder.Callback sh_callback  = null;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main); 
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		surface_view = (SurfaceView) findViewById(R.id.surfaceView1);
		if (surface_holder == null) {
			surface_holder = surface_view.getHolder();
		}
		sh_callback = my_callback();
		surface_holder.addCallback(sh_callback);
	}

	public void onClick(View view) {
		Camera.Parameters p = mCamera.getParameters();
		p.set("jpeg-quality", 100);
		p.setRotation(90);
		mCamera.setParameters(p);
		mCamera.takePicture(null, null, new PhotoHandler(getApplicationContext()));
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	SurfaceHolder.Callback my_callback() {      
		SurfaceHolder.Callback ob1 = new SurfaceHolder.Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				mCamera.stopPreview();
				mCamera.release();
				mCamera = null;
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {

				mCamera = Camera.open();
				Camera.Parameters p = mCamera.getParameters();
				p.set("jpeg-quality", 100);
				p.setRotation(90);
				mCamera.setParameters(p);
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)  mCamera.setDisplayOrientation(90);
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) mCamera.setDisplayOrientation(180);
				try {
					mCamera.setPreviewDisplay(holder); 
				} catch (IOException exception) {  
					mCamera.release();  
					mCamera = null;  
				}
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				mCamera.startPreview();
			}
		};
		return ob1;
	}
}
